package com.highveldsky.gwtdatabinding.server.data;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
import com.highveldsky.gwtdatabinding.shared.model.Car;

public class DAO {

	private static DAO singleton;
	private Objectify db;
	private static final Logger log = Logger.getLogger(DAO.class.getName());

	public static DAO getInstance() {
		if (singleton==null) {
			singleton = new DAO();
		}
		return singleton;
	}
	
	private DAO() {
		log.fine("Creating DAO");
		ObjectifyService.register(Car.class);
		db = ObjectifyService.begin();
	}

	public Long createCar(Car car) {
		log.fine("Creating car: "+car);
		db.put(car);
		log.fine("Created with id: "+car.getId());
		return car.getId();
	}

	public void deleteCar(Long id) {
		log.fine("Deleting car: "+id);
		db.delete(Car.class, id);
	}

	public void updateCar(Car car) {
		log.fine("Updating car: "+car);
		db.put(car);
	}

	public Car readCar(Long id) {
		log.fine("Reading car: "+id);
		return db.get(Car.class, id);
	}

	public List<Car> listCars() {
		log.fine("Listing cars");
		Query<Car> q = db.query(Car.class);
		List<Car> result = new ArrayList<Car>();
		for (Car c : q) {
			log.fine(c.toString());
			result.add(c);
		}
		return result;
	}

}
